import { create } from 'zustand';
import { persist } from 'zustand/middleware';

const MAX_MESSAGES = 100; // 最大保存消息数量

const useChatStore = create(
  persist(
    (set) => ({
      messages: [],
      isVoiceMode: false,
      isRecording: false,
      currentVoiceText: '',
      isAIResponding: false,
      addMessage: (message) => set((state) => {
        const newMessages = [...state.messages, message];
        // 如果消息数量超过限制，删除最旧的消息
        if (newMessages.length > MAX_MESSAGES) {
          newMessages.shift();
        }
        return { messages: newMessages };
      }),
      setVoiceMode: (mode) => set({ isVoiceMode: mode }),
      setRecording: (recording) => set({ isRecording: recording }),
      setCurrentVoiceText: (text) => set({ currentVoiceText: text }),
      setAIResponding: (responding) => set({ isAIResponding: responding }),
      clearMessages: () => set({ messages: [] }),
    }),
    {
      name: 'chat-storage', // localStorage 的 key
      partialize: (state) => ({ messages: state.messages }), // 只持久化 messages
    }
  )
);

export default useChatStore; 